package com.store.practice.service.impl;

import com.store.practice.mapper.AppAccountMapper;
import com.store.practice.mapper.BgStoreStaffMapper;
import com.store.practice.model.AppAccount;
import com.store.practice.model.BgStoreStaff;
import com.store.practice.model.BgStoreStaffExample;
import com.store.practice.service.SettingsManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SettingsManageServiceImpl implements SettingsManageService {
    @Autowired
    private AppAccountMapper accountMapper;
    @Autowired
    private BgStoreStaffMapper staffMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Map getAccount(Integer id) {
        HashMap<String, Object> result = new HashMap<>();
        BgStoreStaffExample example = new BgStoreStaffExample();
        example.createCriteria().andAccountIdEqualTo(id);
        List<BgStoreStaff> staffs = staffMapper.selectByExample(example);
        if (staffs!=null&&staffs.size()>0){
            BgStoreStaff staff = staffs.get(0);
            result.put("header",staff.getPicture());
            result.put("name",staff.getName());
            return result;
        }
        return null;
    }

    @Override
    public int update(Integer id, String oldPw, String newPw) {
        AppAccount account = accountMapper.selectByPrimaryKey(id);
        if (!passwordEncoder.matches(oldPw,account.getPassword())){
            return -1;
        }
        account.setPassword(passwordEncoder.encode(newPw));
        return accountMapper.updateByPrimaryKey(account);
    }

}
